
#ifndef __FILEPACKAGE_H__
#define __FILEPACKAGE_H__

#include "FileSect.h"
#include "HashCommon.h"
#include <vector>
#include <fstream>
#include  <sys/stat.h> 

using namespace std;

enum
{
	HASHFLAG_COMMON = 1,
	HASHFLAG_NOT_USED = -1,
};

struct SHashTableItem
{
	unsigned long m_iHashValue;
	unsigned long m_iName1;
	unsigned long m_iName2;
	int m_iSectIndex;
	int m_iFlag;
	SHashTableItem()
	{
		m_iName1     = 0;
		m_iName2     = 0;
		m_iHashValue = 0;

		m_iSectIndex = 0;
		m_iFlag      = HASHFLAG_NOT_USED;
	}
};

struct SPackageHeader
{
	char m_keyChar[4]; /// yyy
	int  m_nVersion;/// 1000
	int  m_nHashTableSize;
	int  m_nSectSize;

	SPackageHeader()
	{
		m_nHashTableSize = 0;
		m_nSectSize = 0;

	}

};
class CFilePackage
{
	friend class CFileSect;
private:
	SHashTableItem      *m_pHashTable;
	vector<CFileSect *>  m_listSect;
	SPackageHeader       m_sHeader;
	int                  m_iWriterSeekPos;
	ofstream             m_fileWriter;
	ifstream             m_fileReader;
	CHashCommon          m_hashCommon;
public:
	CFilePackage()
	{
		m_pHashTable = NULL;
		m_iWriterSeekPos = 0;
	}
	virtual ~CFilePackage()
	{
		delete[] m_pHashTable;
		m_pHashTable = NULL;
	}

	bool initHashTable( int iSize );

	bool addSectItem( const char * name );
	char * getSectData( const char * name, int & _dataLen );

	
	bool open( const char * fileName );
	bool save( const char * fileName );
	bool save_2_file( const char *name, const char * fileName );

	void close();

protected:
	int _writeData( unsigned long _iOffset, unsigned long _iLen, char *buf );
	int _readData( unsigned long _iOffset, unsigned long _iLen, char *buf );
private:
	bool __resizeHashTable( int _hashTableSize );
	int  __findHashIndex( const char * name );

	bool __readHeader( );
	bool __readHashTable();
	bool __readSectInfo( );

	bool __writeHeader( );
	bool __writeHashTable( );
	bool __writeSectInfo( );
	bool __writeData();
	unsigned long  __calSectsOffset();
	void __calHashTable();
	void __fitHashTable();

	void __write( const char *_Str, streamsize _count );
	void __read( char *_Str, streamsize _count );

};

#endif // __FILEPACKAGE_H__